package com.dwx.shopping_mall.service.impl;

import com.dwx.shopping_mall.entity.Wallet;
import com.dwx.shopping_mall.entity.WalletDetails;
import com.dwx.shopping_mall.mapper.WalletDetailsMapper;
import com.dwx.shopping_mall.mapper.WalletMapper;
import com.dwx.shopping_mall.service.WalletDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class WalletDetailsServiceImpl implements WalletDetailsService {

    @Autowired
    private WalletDetailsMapper walletDetailsMapper;
    @Autowired
    private WalletMapper walletMapper;


    @Transactional
    @Override
    public Integer addTransaction(WalletDetails walletDetails) {
        Wallet wallet = walletMapper.queryWallerbyId(walletDetails.getWalletId());
        Integer walletId = walletDetails.getWalletId();
        BigDecimal amount = walletDetails.getAmount();
        if (walletDetails.getTransactionMode() == 0) {   // 支出
            if (wallet.getBalance().compareTo(walletDetails.getAmount()) > -1) {
                walletMapper.updateBalance(walletId,amount.negate(),new Date());
            }else return null;
        }else if (walletDetails.getTransactionMode() == 1){ //转入
            walletMapper.updateBalance(walletId,amount,new Date());
        }
        walletDetails.setCreateDate(new Date());
        return walletDetailsMapper.addTransaction(walletDetails);
    }

    /**
     * 查询用户钱包金额变动明细的接口，按时间降序排列
     */
    @Override
    public List<WalletDetails> queryWalletDetails(Integer walletId) {
        return walletDetailsMapper.queryWalletDetails(walletId);
    }
}
